package com.evil.QuartzJob;

import com.evil.Bean.AnswerOverItemBean;
import com.evil.DAO.AnswerOverItemDAO;
import com.evil.Log.OverItemListLog;
import com.evil.Mail.MailBean;
import com.evil.Mail.SendMail;
import com.evil.Utils.PropertiesUtils;
import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import javax.mail.MessagingException;
import java.io.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

/********************************************
 * 工程名：Web
 * 包名：com.evil.QuartzJob
 * 时间：16-9-20 下午5:21
 * 作者：白雨濃 evil
 * 邮箱：evilbai@foxmail.com
 * 内容：每天1:00生成前一天的答题情况log，保存在文档/logs/overitemlog
 ********************************************/
public class CreateOverItemLogsJob implements Job
{
    private static Logger log = Logger.getLogger(CreateOverItemLogsJob.class);
    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");

    @Override
    public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException
    {
        log.info(dateFormat.format(new Date()) + ":" + "开始输出前一天用户答题情况。"+"\r\n");

        getLastDayOverItem();
    }

    /**
     * 获得前一天的用户答题情况
     */
    public void getLastDayOverItem()
    {
        String path = this.getClass().getClassLoader().getResource("").getPath().replace("WEB-INF/classes/", "");

        String text = "";
        String space = "       ";
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd 00:00:00");

        Date today = null;
        Date yesterday = null;

        try
        {
            today = dateFormat.parse(dateFormat.format(new Date()));
            yesterday = dateFormat.parse(dateFormat.format(getYesterday()));
        }
        catch (ParseException e)
        {
            e.printStackTrace();
        }

        AnswerOverItemDAO dao = new AnswerOverItemDAO();

        ArrayList<AnswerOverItemBean> list = dao.getListByDate(yesterday, today);

        try
        {
            if (createDir(path + "logs/overItem"))
                writeFile(
                        path + "logs/overItem/" +
                                new SimpleDateFormat("yyyyMMdd")
                                        .format(getYesterday()) +
                                "用户答题情况表.html"
                        , new OverItemListLog(new SimpleDateFormat("yyyyMMdd")
                                .format(getYesterday()) +
                                "用户答题情况表"/*标题*/
                                , 100/*总用户量*/
                                , 100/*日答题量*/
                                , 100/*日推送总流量*/
                                , new Gson().toJson(list)).getHtml()/*用户答题详情JSON*/
                );
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
    }

    /**
     * 获得昨天
     *
     * @return 昨天date
     */
    private Date getYesterday()
    {
        Date yesterday = new Date();
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(yesterday);
        calendar.add(Calendar.DATE, -1);//把日期往后增加一天.整数往后推,负数往前移动
        yesterday = calendar.getTime();   //这个时间就是日期往后推一天的结果
        return yesterday;
    }

    /**
     * 写入文件
     *
     * @param fileName    文件名
     * @param fileContent 文件内容
     */
    private void writeFile(String fileName, String fileContent)
    {
        File file = null;
        try
        {
            file = new File(fileName);
            log.info(dateFormat.format(new Date()) + ">>>"
                    + "文件目录：" + file.getCanonicalPath()+"\r\n");
            if (!file.exists())
                file.createNewFile();
            OutputStreamWriter write = new OutputStreamWriter(new FileOutputStream(file), "utf-8");
            BufferedWriter writer = new BufferedWriter(write);
            writer.write(fileContent);
            writer.close();
            log.info(dateFormat.format(new Date()) + ">>>"
                    + "文件写入成功"+"\r\n");

            /*发送邮件*/
            {
                MailBean bean = new MailBean();
                PropertiesUtils utils = new PropertiesUtils();
                /*bean.setFromAddr("evilbai@sina.com");
                bean.setUserPassword("evil1714698245");
                bean.setToAddr("evilbai@foxmail.com");*/

                String addr = utils.get("sendmail.from.addr");
                String password = utils.get("sendmail.from.password");
                String toAddr = utils.get("sendmail.to");

                bean.setFromAddr(addr);
                bean.setUserPassword(password);
                bean.setToAddr(toAddr);

                bean.setTitle(file.getName());
                bean.setContent(file.getName());
                bean.setFile(file);

                new SendMail().sendFile(bean);
                log.info(dateFormat.format(new Date()) + ">>>"
                        + file.getName() + "邮件发送成功"+"\r\n");
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
            log.info(dateFormat.format(new Date()) + ">>>"
                    + file.getName() + "本地保存失败"+"\r\n");
        }
        catch (MessagingException e)
        {
            e.printStackTrace();
            log.info(dateFormat.format(new Date()) + ">>>"
                    + file.getName() + "邮件发送失败"+"\r\n");
        }
    }

    /**
     * 新建文件夹
     *
     * @param destDirName
     * @return
     */
    private boolean createDir(String destDirName)
    {
        File dir = new File(destDirName);
        if (dir.exists())
            //System.out.println("创建目录" + destDirName + "失败，目标目录已经存在");
            return true;
        if (!destDirName.endsWith(File.separator))
            destDirName = destDirName + File.separator;
        //创建目录
        if (dir.mkdirs())
        {
            System.out.println("创建目录" + destDirName + "成功！");
            return true;
        }
        else
        {
            System.out.println("创建目录" + destDirName + "失败！");
            return false;
        }
    }


}
